import httplib2
import urllib
import sys
from xml.etree import ElementTree

search_url = 'http://210.72.4.33/interlib/websearch/bookSearch'
client = httplib2.Http(".cache")

def search_book_list(keyword):
    args = {'pageNo' : '1',
            'filter' : '(title:' + keyword +')',
            'cmdACT' : 'list',
            'xsl' : 'BOOK_list.xsl',
            'mod' : 'oneXSL',
            'columnID' : '1',
            'searchSign' : '',
            'libNUM' : '8',
            'ISFASTSEARCH' : 'true',
            'col1' : 'title',
            'val1' : keyword,
            'matching' : 'radionbutton',
            'marcformat' : 'all',
            'booktype' : 'all',
            'startPubdate' : '',
            'endPubdate' : '',
            'raws' : '10',
            'sortSign' : 'score_sort',
            'orderSign' : 'true'
            }
    body = urllib.urlencode(args)
    headers = {'Content-Type' : 'application/x-www-form-urlencoded'}
    resp, content = client.request(search_url, 'POST', body, headers)
    return content
    
def parse_search_result(xml):
    doc = ElementTree.fromstring(xml)
    for book in doc.findall('ROW'):
        print "%s" % (book.attrib['cnt'])
        iter = book.getchildren()
        for ele in iter:
            print "%s : %s" % (ele.tag, ele.text)
        print

def get_book_num(bookrecno):
    args = {'cmdACT' : 'getbooknum',
            'fill' : ",'" + bookrecno + "'"}
    url = search_url + "?" + urllib.urlencode(args)
    resp, content = client.request(url)
    print content

def get_book_detail(bookrecno):
    args = {'cmdACT' : 'detailmarc',
            'bookrecno' : bookrecno}
    url = search_url + "?" + urllib.urlencode(args)
    resp, content = client.request(url)
    return content

def parse_book_detail(xml):
    doc = ElementTree.fromstring(xml)
    rowset = doc.findall('ROWSET1')[0]
    for book in rowset.findall('ROW'):
        iter = book.getchildren()
        for ele in iter:
            print "%s : %s" % (ele.tag, ele.text)
        print

if (len(sys.argv) < 3):
    print 'Option error!'
    print '--search [keyword]'
    print '--detail [bookrecno]'
    exit()
elif sys.argv[1] == '--search':
    xml = search_book_list(sys.argv[2])
    parse_search_result(xml)
elif sys.argv[1] == '--detail':
    xml = get_book_detail(sys.argv[2])
    parse_book_detail(xml)
